package priv.wjh.study.cloud.feign.config;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import priv.wjh.study.cloud.feign.api.JsonUtil;
import priv.wjh.study.cloud.feign.api.config.GenericResult;
import priv.wjh.study.cloud.feign.api.config.GenericWrapper;

/**
 * //TODO
 *
 * @author wangjunhao
 **/
@ControllerAdvice
public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return methodParameter.hasMethodAnnotation(GenericResult.class);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (null == o) {
            return null;
        }
        GenericWrapper genericWrapper = new GenericWrapper();
        genericWrapper.setClassName(o.getClass().getName());
        genericWrapper.setBody(JsonUtil.toJson(o));
        ((ServletServerHttpResponse) serverHttpResponse).getServletResponse()
                .setHeader("generic", "true");
        return genericWrapper;
    }
}
